<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <div class="w-1/4 xl:w-1/5 left-box">
      <div class="left-btn-box">
        <a-button type="primary" @click="handleImport">导入产品BOM</a-button>
        <a-button @click="handleExport">导出产品BOM</a-button>
        <a-button type="primary" @click="handleCreate(true)">新增</a-button>
      </div>
    </div>
    <div class="w-3/4 xl:w-4/5 mr-2 bg-white">
      <BasicTable @register="registerCurrentTable" class="current-box" v-if="hasMaterialInfo">
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                icon: 'clarity:note-edit-line',
                onClick: handleCurrentEdit.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </BasicTable>
      <BasicTable @register="registerSubTable" v-if="hasMaterialInfo">
        <template #toolbar>
          <a-button type="primary" @click="handleCreate(false)"> {{ t('新增') }} </a-button>
        </template>
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                icon: 'clarity:note-edit-line',
                onClick: handleSubEdit.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </BasicTable>
    </div>
    <ImportModal
      @register="registerImportModal"
      importUrl="/caseErpBom/caseErpBom/import"
      @success="reload"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, createVNode, nextTick } from 'vue';
  import { BasicTable, useTable, TableAction, BasicColumn } from '/@/components/Table';
  import {
    getBomInfo,
    exportInfo,
    downloadTemplate,
    deleteBomMaterial,
  } from '/@/api/erp/bom/product';

  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ImportModal } from '/@/components/Import';
  import { useModal } from '/@/components/Modal';
  import { downloadByData } from '/@/utils/file/download';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const columns: BasicColumn[] = [
    {
      title: '物料编号',
      dataIndex: 'code',
    },
    {
      title: '物料名称',
      dataIndex: 'name',
    },
    {
      title: '规格型号',
      dataIndex: 'model',
      width: 100,
    },
    {
      title: '物料类别',
      dataIndex: 'typeName',
      width: 150,
    },
    {
      title: '数量',
      dataIndex: 'count',
      width: 100,
    },
    {
      title: '单位',
      dataIndex: 'unitName',
      width: 100,
    },
    {
      title: '物料属性',
      dataIndex: 'propertyName',
    },
  ];

  const { notification } = useMessage();

  const selectBomId = ref('');
  const subDataSource = ref([]);
  const treeRef = ref();
  const hasMaterialInfo = ref(false);

  const [registerModal, { openModal }] = useModal();
  const [registerImportModal, { openModal: openImportModal }] = useModal();

  const [registerCurrentTable, { reload: reloadCurrentTable }] = useTable({
    title: '当前物料信息',
    api: getBomInfo,
    rowKey: 'id',
    columns,
    beforeFetch: () => {
      return { id: selectBomId.value };
    },
    afterFetch: (res) => {
      subDataSource.value = res.length ? res[0].childList || [] : [];
    },
    striped: false,
    showIndexColumn: false,
    pagination: false,
    actionColumn: {
      width: 80,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });
  const [registerSubTable, { reload: reloadSubTable }] = useTable({
    title: '子级物料信息',
    dataSource: subDataSource,
    rowKey: 'id',
    columns,
    striped: false,
    showIndexColumn: false,
    pagination: false,
    actionColumn: {
      width: 80,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  function handleCreate(isFirst) {
    openModal(true, {
      isUpdate: false,
      parentId: isFirst ? '' : selectBomId.value,
    });
  }

  function handleSubEdit(record: Recordable) {
    openModal(true, {
      id: record.id,
      isUpdate: true,
      parentId: selectBomId.value,
    });
  }

  function handleCurrentEdit(record: Recordable) {
    openModal(true, {
      id: record.id,
      isUpdate: true,
    });
  }

  const handleDelete = (record: Recordable) => {
    Modal.confirm({
      title: t('提示信息'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('是否确认删除？'),
      okText: t('确认'),
      cancelText: t('取消'),
      async onOk() {
        await deleteBomMaterial(record.id);
        notification.success({
          message: t('提示'),
          description: t('删除成功'),
        });
        reload();
      },
      onCancel() {},
    });
  };

  const handleSelect = (id = '') => {
    selectBomId.value = id;
    hasMaterialInfo.value = !!selectBomId.value;
    if (hasMaterialInfo.value) {
      nextTick(() => {
        reloadCurrentTable();
      });
    }
  };

  const handleImport = () => {
    openImportModal(true, {
      title: t('快速导入'),
      api: downloadTemplate,
      templateTitle: '产品BOM模板',
    });
  };
  const handleExport = async () => {
    const res = await exportInfo();
    downloadByData(
      res.data,
      '产品BOM.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
  };

  const reload = () => {
    reloadCurrentTable();
    reloadSubTable();
    treeRef.value.fetch();
  };
</script>
<style lang="less" scoped>
  .left-box {
    margin-right: 8px;
    overflow: hidden;
    background: #fff;
    height: 100%;

    .left-btn-box {
      margin: 10px 8px 0;

      :deep(.ant-btn) {
        padding: 4px 10px;
        font-size: 12px;
        border-radius: 3px;
        margin-right: 5px;

        &:nth-child(2) {
          color: #fff;
          background: #e6a23c;
          border-color: #e6a23c;
        }
      }
    }
  }

  .current-box {
    height: 180px;
    overflow: hidden;
  }
</style>
